package com.ws.app.common;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSON;
import net.sf.json.JSONSerializer;

public class ControllerSupport {

    public static final String CONTENTTYPE_JSON = "application/json;charset=utf-8";

    public static final String CONTENTTYPE_TEXT = "text/plain;charset=utf-8";

    public static final String CONTENTTYPE_HTML = "text/html;charset=utf-8";

    public static final String CONTENTTYPE_XML = "text/xml;charset=utf-8";

    // application/javascript
    public static final String CONTENTTYPE_JAVASCRIPT = "text/javascript;charset=utf-8";

    protected void outputJSON(Object output, HttpServletResponse resp) {
        JSON json = JSONSerializer.toJSON(output);
        output(json.toString(), resp, CONTENTTYPE_JSON);
    }

    protected void outputText(String output, HttpServletResponse resp) {
        output(output, resp, CONTENTTYPE_TEXT);
    }

    protected void outputXml(Object output, HttpServletResponse resp) {
        output(output.toString(), resp, CONTENTTYPE_XML);
    }

    protected void outputHtml(String output, HttpServletResponse resp) {
        output(output, resp, CONTENTTYPE_HTML);
    }

    protected void outputJavascript(String output, HttpServletResponse resp) {
        output(output, resp, CONTENTTYPE_JAVASCRIPT);
    }

    protected void output(String output, HttpServletResponse resp,
            String contentType) {
        // write
        PrintWriter wr = null;
        try {
            // Response
            resp.setHeader("Pragma", "no-cache");
            resp.addHeader("Cache-Control", "must-revalidate");
            resp.setHeader("Cache-Control", "no-cache");
            resp.setHeader("Cache-Control", "no-store");
            resp.setDateHeader("Expires", 0);
            // Set Encoding.
            resp.setContentType(contentType);
            resp.setCharacterEncoding("utf-8");
            wr = resp.getWriter();
            wr.write(output);
            wr.flush();
            wr.close();
        } catch (IOException e) {
            new WSAppException(e);
        } finally {
            if (wr != null) {
                wr.close();
            }
        }
    }
}
